package com.promise.jokerdream.work.signin.after

import com.promise.jokerdream.manager.ExecutionHistoryManager
import com.promise.jokerdream.repository.GameApi
import com.promise.jokerdream.repository.PhoneGameApi
import com.promise.jokerdream.repository.foldWithApiException
import com.promise.jokerdream.utils.AppContext
import com.promise.jokerdream.work.BaseWork
import com.promise.jokerdream.work.WorkResult

// 分享工作
class PenguinShareWork(uin: String): BaseWork(uin) {

    override val name: String
        get() = "分享"

    override val priority: Int
        get() = 7
    
    private val gameApi = GameApi.getInstance()
    private val phoneGameApi = PhoneGameApi.getInstance()
    private val historyManager by lazy { ExecutionHistoryManager.getInstance(AppContext.get()) }
    
    override suspend fun executeWork(): WorkResult {
        return try {
            // 1. 查询PC分享信息
            val shareInfoResult = gameApi.queryPenguinShare()
            shareInfoResult.foldWithApiException(
                onSuccess = { shareInfo ->
                    // 检查是否有未分享的项目且今日分享次数未满
                    val hasUnsharedItems = shareInfo.shareInfos.any { it.canShare == 1 }
                    val isTodayShareNotFull = shareInfo.dayShareTimes < shareInfo.dayMaxShareTimes
                    
                    if (hasUnsharedItems && isTodayShareNotFull) {
                        // 2. 执行phone一键分享
                        val shareResult = phoneGameApi.shareGame()
                        shareResult.foldWithApiException(
                            onSuccess = { response ->
                                historyManager.addHistory(name, response.actionResult)
                                WorkResult.Success
                            },
                            onFailure = { code, msg ->
                                historyManager.addHistory(name, msg, code)
                                WorkResult.Failure(Exception(msg), msg)
                            }
                        )
                    } else {
                        // 没有未分享的项目或今日分享次数已满
                        WorkResult.Success
                    }
                },
                onFailure = { code, msg ->
                    historyManager.addHistory(name, msg, code)
                    WorkResult.Failure(Exception(msg), msg)
                }
            )
        } catch (e: Exception) {
            historyManager.addHistory(name, e.message)
            WorkResult.Failure(e, e.message)
        }
    }
}